<template>
  <div>
    <el-dialog
      title="图片上传"
      v-loading="uploadLoding"
      :close-on-click-modal="false"
      @close="closeHandle"
      :visible.sync="visible"
    >
      <div class="upLoadcontent">
        <div class="upLoadleft">
          <div class="groupList" v-loading="dataListLoading">
            <div
              :class="{ on: active === index }"
              :key="index"
              v-for="(item, index) in groupList"
            >
              <span @click="selectGroup(index, item)">{{
                item.groupName
              }}</span>
              <i class="el-icon-close" @click="delGroup(item)"></i>
            </div>
          </div>

          <div>
            <el-button type="text" @click="dialogVisible = true"
              >添加分组</el-button
            >
          </div>
        </div>
        <div class="upLoadRight">
          <div class="topBtn">
            <div>
              <el-dropdown @command="moveGroup">
                <el-button type="primary">
                  移动至
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(item, index) in groupList"
                    :command="item"
                    :key="index"
                    >{{ item.groupName }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
              <el-button
                @click="delImg"
                v-loading.fullscreen.lock="fullscreenLoading"
                >删除</el-button
              >
            </div>
            <div>
              <el-upload
                :show-file-list="false"
                class="upload-demo"
                action=""
                :http-request="uploadFile"
                multiple
              >
                <el-button size="small" type="primary">+上传图片</el-button>
              </el-upload>
            </div>
          </div>
          <div class="imgWrap">
            <el-checkbox-group
              v-loading="ImgListLoding"
              v-model="checkListImg"
              class="imgItem"
            >
              <el-checkbox
                :label="item"
                :value="item"
                v-for="item in fileList"
                :key="item.id"
                ><img :src="item.fileUrl" alt=""
              /></el-checkbox>
            </el-checkbox-group>
            <el-pagination
              @size-change="sizeChangeHandle"
              @current-change="currentChangeHandle"
              :current-page="page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="size"
              :total="totalPage"
              layout="total, sizes, prev, pager, next, jumper"
            ></el-pagination>
          </div>
          <div class="bottom_btn">
            <el-button @click="chooseImg" type="primary">确定</el-button>
            <el-button @click="closeHandle">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="新增图片分组"
      :visible.sync="dialogVisible"
      width="50%"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item prop="groupName" label="分组名称"
          ><el-input v-model="ruleForm.groupName"></el-input
        ></el-form-item>
        <el-form-item prop="sort" label="排序"
          ><el-input v-model="ruleForm.sort" type="number"></el-input
        ></el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelModel">取 消</el-button>
        <el-button type="primary" @click="submitModel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import publicService from '../../../api/publicService'
import axios from 'axios'
import Vue from 'vue'
export default {
  data() {
    return {
      visible: false,
      url: '',
      dialogVisible: false,
      num: 0,
      active: 0,
      loading: false,
      fullscreenLoading: false,

      ImgListLoding: false,
      uploadLoding: false,
      percentage: 0,
      successNum: 0,
      checkListImg: [],
      selectGroupId: '',
      ruleForm: {
        groupName: ''
      },
      dataListLoading: false,
      rules: {
        groupName: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            required: true,
            message: '请输入排序',
            trigger: 'blur'
          }
        ]
      },
      groupList: [],
      token: '',
      fileList: [],
      page: 1,
      size: 10,
      totalPage: 0
    }
  },
  created() {
    this.token = JSON.parse(sessionStorage.getItem('token'))
  },
  methods: {
    // 每页数
    sizeChangeHandle(val) {
      this.size = val
      this.page = 1
      this.getImgList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.page = val

      this.getImgList()
    },

    async moveGroup(val) {
      if (this.checkListImg.length <= 0) {
        layer.alert('请先选择需要移动的图片')
      } else {
        let res = await publicService.moveGrpIds({
          ids: this.checkListImg.map(val => val.fileId).toString(),
          grpId: val.groupId
        })
        if (res) {
          layer.alert(res.data.msg)
          this.init()
        }
      }
    },
    chooseImg() {
      this.closeHandle()
      this.$emit('selectImgList', this.checkListImg)
    },
    delImg() {
      if (this.checkListImg.length > 0) {
        layer.confirm(
          '是否删除这条数据？',
          {
            btn: ['取消', '确定'] // 按钮
          },
          index => {
            layer.close(index)
          },
          async () => {
            this.fullscreenLoading = true

            let res = await publicService.delFileByIds(
              this.checkListImg.map(val => val.fileId).toString()
            )
            if (res) {
              this.fullscreenLoading = false

              layer.alert(res.data.msg)
              this.init()
            }
          }
        )
      } else {
        layer.alert('请先选择需要删除的图片')
      }
    },

    // 删除分组
    async delGroup(row) {
      layer.confirm(
        '是否删除这条数据？',
        {
          btn: ['取消', '确定'] // 按钮
        },
        index => {
          layer.close(index)
        },
        async () => {
          let res = await publicService.grpDel(row.groupId)
          if (res) {
            layer.alert(res.data.msg)
            this.init()
          }
        }
      )
    },
    // 分组切换
    selectGroup(index, row) {
      this.active = index
      this.selectGroupId = row.groupId
      this.page = 1
      this.getImgList(row.groupId)
    },
    // 图片上传
    uploadFile(file) {
      this.formData = new FormData()

      let config = {
        headers: {
          token: Vue.cookie.get('token'),
          'Content-Type': 'multipart/form-data'
        }
      }
      this.formData.append('file', file.file)
      this.uploadLoding = true
      axios
        .post(
          `${this.$config.SERVER_URL}/admin/sys/oss/upload`,
          this.formData,
          config
        )
        .then(res => {
          this.uploadLoding = false
          if (res.data.code == 200) {
            this.fileList.push(res.data.fileVo)
            layer.alert('上传成功')
          } else {
            layer.alert('上传失败')
          }
        })
        .catch(res => {
          this.uploadLoding = false
        })
    },
    // 新增分组
    submitModel() {
      this.$refs['ruleForm'].validate(async valid => {
        if (valid) {
          let res = await publicService.grpUpdate({
            groupName: this.ruleForm.groupName,
            sort: this.ruleForm.sort,
            groupId: ''
          })
          if (res) {
            this.dialogVisible = false
            this.cancelModel()
            layer.alert(res.data.msg)
            this.init()
          }
        } else {
          return false
        }
      })
    },
    // 关闭分组模态框 清空表单
    cancelModel() {
      this.dialogVisible = false
      this.$refs['ruleForm'].resetFields()
    },
    // 初始化获取分组，和组下面的图片
    async init(row) {
      this.checkListImg = []
      this.dataListLoading = true
      this.visible = true
      let res = await publicService.grpList()
      this.dataListLoading = false

      if (res && res.data.code == 200 && res.data.data.length > 0) {
        this.groupList = res.data.data
        this.selectGroupId = this.groupList[this.active].groupId
        this.getImgList(this.groupList[this.active].groupId)
      } else {
        this.groupList = []
      }
    },
    // 得到某分组下的图片
    async getImgList() {
      this.ImgListLoding = true

      let res = await publicService.getImgList({
        grpId: this.selectGroupId,
        page: this.page,
        size: this.size
      })
      this.ImgListLoding = false
      if (res) {
        this.totalPage = res.data.total
        this.fileList = res.data.data
        if (this.fileList.length == 0 && this.page > 1) {
          this.page--
          this.getImgList()
        }
      }
    },

    // 弹窗关闭时
    closeHandle() {
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.upLoadcontent {
  display: flex;

  .upLoadleft {
    margin-right: 20px;
    width: 15%;

    .groupList {
      display: flex;
      flex-direction: column;
      height: 300px;
      overflow-y: scroll;

      .on {
        background: #57b4a3;
        color: #fff;
      }

      div {
        border-radius: 5px;
        padding: 10px;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;

        span {
          width: 130px;
        }
      }
    }
  }

  .upLoadRight {
    width: 85%;

    .topBtn {
      display: flex;
      justify-content: space-between;
      width: 100%;
    }

    .imgWrap {
      width: 100%;
      height: 264px;

      margin-top: 20px;
      overflow-y: scroll;

      .imgItem {
        margin-right: 10px;
        margin-bottom: 10px;
        display: flex;

        align-items: center;
        display: flex;
        flex-wrap: wrap;

        /deep/ .el-checkbox {
          height: 176px;
          margin-left: 0;
          margin-bottom: 10px;
        }

        /deep/ .el-checkbox__input {
          position: relative;
          left: 24px;
          top: -75px;
        }

        cursor: pointer;

        img {
          width: 147px;
          height: 167px;
        }
      }
    }

    .bottom_btn {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
  }
}
</style>
